package fr.castorhoz.isi_connectivity_widget.gps_widget;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.util.Log;
import fr.castorhoz.isi_connectivity_widget.ConnBroadcastReceiver;
import fr.castorhoz.isi_connectivity_widget.ConnButton;
import fr.castorhoz.isi_connectivity_widget.database.DBAdapter;

	public class GPSBroadcastReceiver extends ConnBroadcastReceiver {
	
	/**
	 * appWidgets that need to be notified when a broadcast is received
	 */
	protected static List<Integer> appWidgetIds = new ArrayList<Integer>();
	
	private DBAdapter dbAdapter;
	
	public GPSBroadcastReceiver(Context context) { //ConnButton button) {
		super(context); //button);
		dbAdapter = new DBAdapter(context);
		dbAdapter.open();
		appWidgetIds = dbAdapter.getAppWidgetIdUsingWidget(ConnButton.widgets.gpsWidget.name());
		dbAdapter.close();
	}
	
	/**
	 * Adds the appWidget to the ones that need to be notified when the broadcast receiver receives an event
	 * @param appWidgetId
	 */
	public static void addAppWidget(int appWidgetId) {
		Log.d(GPSBroadcastReceiver.class.getName(), "adding appWidgetId "+appWidgetId+" to GPSBroadcastReceiver");
		appWidgetIds.add(appWidgetId);
	}

	@Override
	public void doOnReceive(Context context, Intent intent) {

		boolean previousState = GPSButton.getGPSStateFromDatabse(context);
		LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);		
		if (previousState != lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Log.i(this.getClass().getName(), "registering gps state : "+lm.isProviderEnabled(LocationManager.GPS_PROVIDER));
			dbAdapter.open();
			dbAdapter.removeGPSWidgetStates();
			dbAdapter.insertGPSWidgetState(String.valueOf(!previousState));
			dbAdapter.close();
			previousState = !previousState;
			hasChanged();
			Log.d(this.getClass().getName(), "GPS state is saved into database");
		}
				
	}

	@Override
	protected List<Integer> getAppWidgetIds() {
		return appWidgetIds;
	}

//	@Override
//	protected void registerItself(Context context) {
//		/*IntentFilter filter = new IntentFilter(LocationManager.GPS_PROVIDER);
//		context.getApplicationContext().registerReceiver(this, filter);
//		Log.d(this.getClass().getName(), "broadcast receiver "+this.getClass().getCanonicalName()+" has registered itself");*/
//	}

	@Override
	public String getBroadcastAction() {
		return GPSButton.PROVIDERS_CHANGED_ACTION;
	}

	@Override
	protected String getWidgetName() {
		return ConnButton.widgets.gpsWidget.name();
	}
	
	

}
